package com.songhq.ctool.tools;

import com.google.gson.*;
import com.intellij.notification.Notification;
import com.intellij.ui.JBColor;
import com.songhq.ctool.utils.NotificationUtil;
import org.apache.commons.lang.StringUtils;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
import org.fife.ui.rsyntaxtextarea.SyntaxConstants;
import org.fife.ui.rtextarea.RTextArea;
import org.quartz.CronExpression;

import javax.swing.text.BadLocationException;
import java.awt.event.MouseEvent;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.intellij.notification.NotificationType.ERROR;

public enum ConvertType {


    JSON(SyntaxConstants.SYNTAX_STYLE_JSON) {
        @Override
        void handle(RSyntaxTextArea input, RSyntaxTextArea output) {
            try {
                if (!input.getText().endsWith("\r\n")){
                    input.append("\r\n");
                }
                // 可以同时解析数组或者Object
                JsonElement element = JsonParser.parseString(input.getText());
                Gson gson = new GsonBuilder().setPrettyPrinting().create();
                output.setText(gson.toJson(element));
                // 格式化成功后定位到第一行
                output.setCaretPosition(0);
                //去除提示信息
                input.setToolTipSupplier(null);
            } catch (JsonSyntaxException ex) {
                String msg = ex.getMessage();
                Matcher matcher = ERROR_PATTERN.matcher(msg);
                if (matcher.find()) {
                    // 行索引从0开始
                    int lineIndex = (Integer.parseInt(matcher.group(1))) - 1;
                    // 设置错误行背景色
                    try {
                        input.addLineHighlight(lineIndex, JBColor.RED);
                    } catch (BadLocationException ignore) {
                    }
                    // 设置提示信息
                    input.setToolTipSupplier((RTextArea rt, MouseEvent me) -> {
                        int offset = 0;
                        try {
                            offset = input.getLineOfOffset(input.viewToModel2D(me.getPoint()));
                        } catch (BadLocationException ignore) {
                        }
                        return offset == lineIndex ? msg : null;
                    });
                    // 定位到失败行
                    input.setCaretPosition(lineIndex);
                }
                NotificationUtil.notify(new Notification("json_format", "Json format", msg, ERROR));
            }
        }
    },

    CRON(SyntaxConstants.SYNTAX_STYLE_NONE){

        @Override
        void handle(RSyntaxTextArea input, RSyntaxTextArea output) {
            String trim = input.getText().trim();
            try {
                SimpleDateFormat dataFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                CronExpression cronExpression = new CronExpression(trim);
                Date date1 = cronExpression.getTimeAfter(new Date());
                String dateString1 = dataFormat.format(date1);
                Date date2 = cronExpression.getTimeAfter(date1);
                String dateString2 = dataFormat.format(date2);
                Date date3 = cronExpression.getTimeAfter(date2);
                String dateString3 = dataFormat.format(date3);
                Date date4 = cronExpression.getTimeAfter(date3);
                String dateString4 = dataFormat.format(date4);
                Date date5 = cronExpression.getTimeAfter(date4);
                String dateString5 = dataFormat.format(date5);
                String nextLine = "\r\n";
                output.setText(dateString1 + nextLine + dateString2 + nextLine + dateString3 + nextLine + dateString4 + nextLine + dateString5  );
            } catch (ParseException e) {
                String msg = e.getMessage();
                NotificationUtil.notify(new Notification("json_format", "Cron_parse", msg, ERROR));
            }
        }
    },



    //todo SQL
    SQL(SyntaxConstants.SYNTAX_STYLE_SQL) {

        @Override
        void handle(RSyntaxTextArea input, RSyntaxTextArea output) {
//            String sql = LogParser.toSql(input.getText());
            //todo
            String sql = "sql parse 输出";
            if (StringUtils.isEmpty(sql)) {
                // 设置错误行背景色
                // 默认设置第一行
                try {
                    input.addLineHighlight(0, JBColor.RED);
                } catch (BadLocationException ignore) {
                }
                // 设置提示信息
                input.setToolTipSupplier((RTextArea rt, MouseEvent me) -> {
                    int offset = 0;
                    try {
                        offset = input.getLineOfOffset(input.viewToModel(me.getPoint()));
                    } catch (BadLocationException ignore) {
                    }
                    return offset == 0 ? "the log you input which without \"Preparing:\" or \"Parameters:\"" : null;
                });
            } else {

//                output.setText(SqlFormatter.format(sql));
// todo
                output.setText(sql);
                // 格式化成功后定位到第一行
                output.setCaretPosition(0);
            }
        }
    },




    TEXT(SyntaxConstants.SYNTAX_STYLE_NONE);

    final String style;

    /**
     * json错误信息正则匹配
     */
    private static final Pattern ERROR_PATTERN = Pattern.compile("line (\\w+) column");

    ConvertType(String syntaxStyleJson) {
        this.style = syntaxStyleJson;
    }

    /**
     * 对文本进行格式化
     * @param input  输入文本域
     * @param output 输出文本域
     */
    void handle(RSyntaxTextArea input, RSyntaxTextArea output) {
        // 默认不做任何处理
        System.out.println("进入处理方法 暂时什么都不处理");
    }





}
